package com.isaac.edu.mvcframework.servlet;

import com.isaac.demo.service.IDemoService;
import com.isaac.edu.mvcframework.annotation.*;
import com.isaac.edu.mvcframework.pojo.Handler;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DiyDispatcherServlet extends HttpServlet {

    private Properties properties = new Properties();

    // 缓存扫描到类的全限定类名
    private List<String> classNames = new ArrayList<>();

    // ioc 容器
    private Map<String, Object> ioc = new HashMap<>();

    // handlerMapping
//    private Map<String, Method> handlerMapping = new HashMap<>();

    private List<Handler> handlerMapping = new ArrayList<>();


    @Override
    public void init(ServletConfig config) throws ServletException {
        // 1. 加载配置文件   springMvc.properties
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        doLoadConfig(contextConfigLocation);

        // 2. 扫描相关类
        doScan(properties.getProperty("scanPackage"));

        // 3. 初始化bean（实现ioc容器，基于注解）
        doInstance();

        // 4. 实现依赖注入
        doAutoWired();

        // 5. 构造HandlerMapping处理器映射器，建立url 和 Method关系
        initHandlerMapping();

        System.out.println("spring Mvc 初始化结束");
        // 6. 等待请求
    }

    /**
     * 构造一个HandlerMapping
     */
    private void initHandlerMapping() {
        if(ioc.isEmpty()){return;}

        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Class<?> aClass = entry.getValue().getClass();
            if (!aClass.isAnnotationPresent(DiyController.class)) {
                continue;
            }
            String baseUrl = "";
            if (aClass.isAnnotationPresent(DiyRequestMapping.class)) {
                DiyRequestMapping annotation = aClass.getAnnotation(DiyRequestMapping.class);
                baseUrl = annotation.value(); //  /demo
            }

            // 获取方法
            Method[] methods = aClass.getMethods();
            for (int i = 0; i<methods.length; i++) {
                Method method = methods[i];
                // 方法没有标识DiyRequestMapping 不做处理
                if (!method.isAnnotationPresent(DiyRequestMapping.class)) {
                    continue;
                }

                DiyRequestMapping annotation = method.getAnnotation(DiyRequestMapping.class);
                String methodUrl = annotation.value(); //  /query
                String url = baseUrl + methodUrl;   // /demo/query
                
                // 如果有@DiySecurity注解
                if(method.isAnnotationPresent(DiySecurity.class)){
                    // url = /demo/query?username=''
                    DiySecurity securityAnnotation = method.getAnnotation(DiySecurity.class);
                    String[] userNames = securityAnnotation.value();
                    for(int j = 0; j < userNames.length ;j ++){
                        String realUrl = url + "\\?name=" + userNames[j];
                        // 把method所有信息封装为handler
                        Handler handler = new Handler(entry.getValue(), method, Pattern.compile(realUrl));
                        calcIndex(handler,method);
                    }
                }else{
                    // 把method所有信息封装为handler
                    Handler handler = new Handler(entry.getValue(), method, Pattern.compile(url));
                    calcIndex(handler,method);
                }
            }
        }
    }

    private void calcIndex(Handler handler, Method method){
        // 计算方法位置信息
        Parameter[] parameters = method.getParameters();//query(HttpServletRequest request, HttpServletResponse response, String name)
        for (int j = 0; j < parameters.length; j++){
            Parameter parameter = parameters[j];
            if(parameter.getType() == HttpServletRequest.class || parameter.getType()==HttpServletResponse.class){
                // 如果是request 和 response对象，那么参数名称写 HttpServletRequest 和 HttpServletResponse
                handler.getParamIndexMapping().put(parameter.getType().getSimpleName(),j);
            }else{
                handler.getParamIndexMapping().put(parameter.getName(),j);
            }
        }
        // 建立 url method 映射关系(用 map 进行缓存)
        handlerMapping.add(handler);
    }

    /**
     * 实现依赖注入
     */
    private void doAutoWired() {
        if (ioc.isEmpty()) {
            return;
        }
        // 遍历ioc对象，有DiyAutoWired注解，
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            // 获取 bean对象中字段信息
            Field[] declaredFields = entry.getValue().getClass().getDeclaredFields(); //  @DiyAutoWired  private IDemoService demoService;
            for (Field declaredField : declaredFields) {
                if (declaredField.isAnnotationPresent(DiyAutoWired.class)) {
                    DiyAutoWired annotation = declaredField.getAnnotation(DiyAutoWired.class);
                    String beanName = annotation.value();
                    if (StringUtils.isBlank(beanName)) {
                        // 未配置具体的bean Id，需要根据当前字段类型注入 IDemoService
                        beanName = declaredField.getType().getName();
                    }
                    // 开启赋值
                    declaredField.setAccessible(true);
                    try {
                        declaredField.set(entry.getValue(), ioc.get(beanName));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }


    // ioc 容器
    // 基于className 缓存的全限定类名，及反射技术，完成对象创建和管理
    private void doInstance() {
        // 1. 空值判断
        if (classNames.size() == 0) {
            return;
        }

        try {
            for (String className : classNames) {
                //com.isaac.demo.controller.DemoController
                // 反射
                Class<?> aClass = Class.forName(className);
                // 区分controller，service
                if (aClass.isAnnotationPresent(DiyController.class)) {
                    // controller的id此处不做过多处理，不取value，类首字母小写作为id，保存到ioc中
                    String simpleName = aClass.getSimpleName();
                    String lowerFirstSimpleName = lowerFirst(simpleName);
                    Object o = aClass.getDeclaredConstructor().newInstance();
                    ioc.put(lowerFirstSimpleName, o);
                } else if (aClass.isAnnotationPresent(DiyService.class)) {
                    DiyService annotation = aClass.getAnnotation(DiyService.class);
                    // 获取注解的value
                    String beanName = annotation.value();
                    if (!StringUtils.isNoneBlank(beanName.trim())) {
                        beanName = lowerFirst(aClass.getSimpleName());
                    }
                    ioc.put(beanName, aClass.getDeclaredConstructor().newInstance());

                    // service层有接口，面向接口开发，因此再以接口名为id，再放一份对象到ioc对象中
                    Class<?>[] interfaces = aClass.getInterfaces();
                    for (Class<?> anInterface : interfaces) {
                        ioc.put(anInterface.getName(), aClass.getDeclaredConstructor().newInstance());
                    }
                } else {
                    // 其他注解未做解析
                    continue;
                }
            }
        } catch (IllegalAccessException | InstantiationException | ClassNotFoundException | NoSuchMethodException | InvocationTargetException e) {
            e.printStackTrace();
        }


    }

    private String lowerFirst(String str) {
        char[] chars = str.toCharArray();
        if ('A' <= chars[0] && chars[0] <= 'Z') {
            chars[0] += 32;
        }
        return String.valueOf(chars);
    }


    // 扫描类
    // scanPackage: com.lagou.demo  package---> 磁盘上的文件夹(fil)探查子目录
    private void doScan(String scanPackage) {
        String s = scanPackage.replaceAll("\\.", "/");
        String scanPackagePath = Objects.requireNonNull(Thread.currentThread().getContextClassLoader().getResource("")).getPath() + s;

        File pack = new File(scanPackagePath);
        File[] files = pack.listFiles();

        for (File file : files) {
            if (file.isDirectory()) {   // 子包
                // 递归
                doScan(scanPackage + "." + file.getName()); // com.lagou.demo.controller
            } else if (file.getName().endsWith(".class")) {
                String className = scanPackage + "." + file.getName().replaceAll(".class", "");
                classNames.add(className);
            }
        }
    }

    // 加载配置文件
    private void doLoadConfig(String contextConfigLocation) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*        // 处理请求： 根据 url，找到对应method方法，进行方法调用
        String requestURI = req.getRequestURI();
        Method method = handlerMapping.get(requestURI);

        // 反射调用，需要传入参数，此处无法完成调用，没有缓存对象，同时有没有参数，需要改造initHandler
        method.invoke()*/

        Handler handler = getHandler(req);

        if(null == handler){
            resp.getWriter().write("404 not found");
            return;
        }

        // 参数绑定
        // 获取所有参数类型数组，数组长度是最后传入args长度
        Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();

        Object[] paraValues = new Object[parameterTypes.length];

        Map<String, String[]> parameterMap = req.getParameterMap();

        // 遍历request中所有参数 （填充除了request，response外的参数）
        for (Map.Entry<String, String[]> stringEntry : parameterMap.entrySet()) {
            // name=1 & name=2  name[1,2]
            String value = StringUtils.join(stringEntry.getValue(), ",");

            // 如果参数和方法中的参数匹配上，填充数据
            if(!handler.getParamIndexMapping().containsKey(stringEntry.getKey())){continue;}
            Integer index = handler.getParamIndexMapping().get(stringEntry.getKey()); // name在第2个位置
            paraValues[index] = value;
        }

        int requestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName());
        paraValues[requestIndex] = req;

        int responseIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName());
        paraValues[responseIndex] = resp;

        // 最终调用handler的method属性
        try {
            handler.getMethod().invoke(handler.getController(), paraValues);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    private Handler getHandler(HttpServletRequest request){
        if(handlerMapping.isEmpty()){
            return null;
        }
        String[] names = request.getParameterValues("name");
        String requestURI = request.getRequestURI();

        for (Handler handler : handlerMapping) {
            for (String name : names) {
                String patternStr = requestURI + "?name=" + name;
                Matcher matcher = handler.getPattern().matcher(patternStr);
                if(!matcher.matches()){continue;}
                return handler;
            }
        }
        return null;
    }

}
